package com.app.mymvp.business.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.base.utils.T;
import com.app.mymvp.R;
import com.app.mymvp.adapter.SearchHistoryAdapter;
import com.app.mymvp.base.BaseActivity;
import com.app.mymvp.customview.MyListView;
import com.app.mymvp.entity.SearchHistoryEntity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity<SearchPresenter, SearchModel> implements SearchContract.View {

    public static final String SEARCH_KEY = "searchKey";

    @BindView(R.id.tv_homehead_location)
    TextView tvHomeheadLocation;
    @BindView(R.id.iv_homehead_location)
    ImageView ivHomeheadLocation;
    @BindView(R.id.iv_homehead_notice)
    ImageView ivHomeheadNotice;
    @BindView(R.id.tv_homehead_right)
    TextView tvHomeheadRight;
    @BindView(R.id.hot_one)
    Button hotOne;
    @BindView(R.id.hot_two)
    Button hotTwo;
    @BindView(R.id.hot_three)
    Button hotThree;
    @BindView(R.id.hot_four)
    Button hotFour;
    @BindView(R.id.hot_five)
    Button hotFive;
    @BindView(R.id.hot_six)
    Button hotSix;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.lv_history)
    MyListView lvHistory;
    @BindView(R.id.tv_clear)
    TextView tvClear;
    @BindView(R.id.et_homehead_search)
    EditText etHomeheadSearch;

    private List<SearchHistoryEntity> searchHistoryEntities=new ArrayList<>();
    private SearchHistoryAdapter searchHistoryAdapter;

    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    presenter.deleteOneData(searchHistoryEntities.get(msg.arg1).getHistoryName());
                    searchHistoryEntities.remove(msg.arg1);
                    searchHistoryAdapter.notifyDataSetChanged();
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void initView() {

        //必须放在initView中先调用否则会空指针，因为BaseActivity的onCreate方法先执行的initView方法
        presenter.initDatebase(this);

        ivHomeheadNotice.setVisibility(View.GONE);
        tvHomeheadRight.setVisibility(View.VISIBLE);
        tvHomeheadRight.setText(getString(R.string.ok));
        ivHomeheadLocation.setVisibility(View.VISIBLE);
        //tvHomeheadLocation.setText(sharePreUtil.loadCurrentProvince());

        searchHistoryAdapter=new SearchHistoryAdapter(this,searchHistoryEntities,handler);
        lvHistory.setAdapter(searchHistoryAdapter);
        lvHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(R.id.tv_history);
                String name = textView.getText().toString();
                toActivity(name);
            }
        });


        // 搜索框的键盘搜索键点击回调
        etHomeheadSearch.setOnKeyListener(new View.OnKeyListener() {// 输入完后按键盘上的搜索键

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = presenter.hasData(etHomeheadSearch.getText().toString().trim());
                    if (!hasData) {
                        presenter.insertData(etHomeheadSearch.getText().toString().trim());

                        presenter.search("");

                    }
                    // TODO 根据输入的内容模糊查询商品，并跳转到另一个界面，由你自己去实现
                    Toast.makeText(SearchActivity.this, "clicked!", Toast.LENGTH_SHORT).show();

                }
                return false;
            }
        });

        // 搜索框的文本变化实时监听
        etHomeheadSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() == 0) {
                    tvTip.setText("搜索历史");
                } else {
                    tvTip.setText("搜索结果");
                }
                String tempName = etHomeheadSearch.getText().toString();
                // 根据tempName去模糊查询数据库中有没有数据

                presenter.search(tempName);

            }
        });



        // 第一次进入查询所有的历史记录
        presenter.search("");

    }

    @OnClick({R.id.tv_homehead_right, R.id.hot_one, R.id.hot_two, R.id.hot_three, R.id.hot_four, R.id.hot_five, R.id.hot_six, R.id.tv_clear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_clear:
                presenter.deleteData();
                presenter.search("");
                break;
            case R.id.tv_homehead_right:
                String key =etHomeheadSearch.getText().toString().trim();
                if (!"".equals(key) && !presenter.hasData(key)) {
                    presenter.insertData(key);
                }
                if (!"".equals(key)) {
                    toActivity(key);
                } else {
                    T.show(SearchActivity.this, "请输入搜索内容！");
                }
                break;
            case R.id.hot_one:
                toActivity("数学");
                break;
            case R.id.hot_two:
                toActivity("英语");
                break;
            case R.id.hot_three:
                toActivity("语文");
                break;
            case R.id.hot_four:
                toActivity("物理");
                break;
            case R.id.hot_five:
                toActivity("化学");
                break;
            case R.id.hot_six:
                toActivity("生物");
                break;

        }
    }

    @Override
    public void toActivity(String key) {
       /* Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
        intent.putExtra(SEARCH_KEY, key);
        startActivity(intent);
        finish();*/
        T.show(this,"跳转对应搜索界面:"+key);

    }

    @Override
    public void showResult(List<SearchHistoryEntity> list) {
        searchHistoryEntities.clear();
        searchHistoryEntities.addAll(list);
        searchHistoryAdapter.notifyDataSetChanged();
    }


}
